<template>
  <div class="notice-user-setting">
    <el-card shadow="never" style="margin-bottom: 20px;">
      <el-button
        type="primary"
        @click="openSettingDialog"
      >
        设置通知人员
      </el-button>
    </el-card>

    <el-card shadow="never">
      <el-table
        v-loading="loading"
        :data="list"
        border
        stripe
      >
        <el-table-column
          type="index"
          align="center"
        />

        <el-table-column
          label="通知类型"
          align="center"
          prop="type.name"
        />

        <el-table-column
          label="人员"
          align="center"
          prop="user_ids"
        >
          <template v-slot="{ row }">
            <el-popover
              placement="top-start"
              title="通知人"
              width="200"
              trigger="click"
            >
              <el-button
                slot="reference"
                type="text"
              >
                查看
              </el-button>
              <template>
                <div>
                  <el-tag
                    v-for="item in row.users"
                    :key="item.id"
                    style="margin: 0 10px 10px 0;"
                  >
                    {{ item.username }}
                  </el-tag>
                </div>
              </template>
            </el-popover>

          </template>
        </el-table-column>

        <el-table-column
          label="创建日期"
          align="center"
          prop="created_at"
        >
          <template v-slot="{ row }">
            {{ timeFormat(row.created_at) }}
          </template>
        </el-table-column>

        <el-table-column label="操作" align="center">
          <template v-slot="{ row }">
            <el-button
              type="primary"
              size="mini"
              @click="openEditDialog(row)"
            >
              编辑
            </el-button>

            <el-button
              type="danger"
              size="mini"
              @click="handleRemove(row.id)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <SettingDialog
      ref="settingDialogRef"
      v-model="form"
      :visible.sync="settingDialogVisible"
      :title="dialogTitle"
      :type-options="noticeTypeFormat"
      width="500px"
      @onConfirm="handleConfirm"
    />
  </div>
</template>
<script>
import {
  getNoticeType,
  getNoticeUserOfSetting,
  setNoticeUser,
  removeNoticeUser,
  editNoticeUser
} from '@/api/v2/noticeSetting'
import dayjs from 'dayjs'
import SettingDialog from '@/views/noticeUserSetting/components/SettingDialog.vue'
export default {
  name: '',
  components: {
    SettingDialog
  },
  data() {
    return {
      noticeType: [],
      list: [],
      form: {
        type: null,
        userIds: []
      },
      settingDialogVisible: false,
      loading: false
    }
  },
  computed: {
    dialogTitle() {
      return this.form?.id ? '编辑通知人员' : '设置通知人员'
    },

    noticeTypeFormat() {
      return this.noticeType.map(item => {
        return {
          value: item.id,
          label: item.name
        }
      })
    }
  },
  created() {
    this.init()
  },
  methods: {
    init() {
      Promise.allSettled([
        this.getNoticeType(),
        this.getNoticeUserList()
      ])
    },

    async getNoticeType() {
      try {
        const res = await getNoticeType()
        this.noticeType = res.data
      } catch (error) {
        throw new Error(error?.response?.data?.message || '通知类型获取失败')
      }
    },

    async getNoticeUserList() {
      this.loading = true
      try {
        const res = await getNoticeUserOfSetting()
        console.log('res --------->', res)
        this.list = res.data
      } catch (error) {
        this.$message.error(error?.response?.data?.message || '信息获取失败')
      } finally {
        this.loading = false
      }
    },

    openSettingDialog() {
      this.settingDialogVisible = true
      this.$nextTick(() => {
        this.form = this.$options.data().form
        this.$refs.settingDialogRef.resetFields()
      })
    },

    openEditDialog(row) {
      this.form.id = row.id
      this.form.type = row.type_id
      this.form.userIds = JSON.parse(row.user_ids)
      this.settingDialogVisible = true
    },

    timeFormat(time) {
      return dayjs(time).format('YYYY-MM-DD HH:mm:ss')
    },

    handleConfirm(e) {
      if (this.form.id) {
        this.editNoticeUserFetch(e)
      } else {
        this.setNoticeUser(e)
      }
    },

    async setNoticeUser(params) {
      try {
        const res = await setNoticeUser({
          ...params,
          userIds: JSON.stringify(params.userIds)
        })
        this.$message.success('设置成功')
        this.settingDialogVisible = false
        this.refresh()
      } catch (error) {
        this.$message.error(error?.response?.data?.message || '设置失败')
      }
    },

    handleRemove(id) {
      console.log('id --------->', id)
      this.$confirm(
        '是否删除该项？',
        '提示',
        {
          type: 'warning',
          showCancelButton: true,
          showConfirmButton: true,
          cancelButtonText: '取消'
        }
      ).then(() => {
        this.removeNoticeUserFetch(id)
      })
    },

    async removeNoticeUserFetch(id) {
      try {
        const res = await removeNoticeUser(id)
        this.$message.success('删除成功')
        this.refresh()
      } catch (error) {
        this.$message.error(error?.response?.data?.message || '删除失败')
      }
    },

    async editNoticeUserFetch(params) {
      try {
        const res = await editNoticeUser({
          id: params.id,
          user_ids: JSON.stringify(params.userIds)
        })
        this.$message.success('修改成功')
        this.settingDialogVisible = false
        this.refresh()
      } catch (error) {
        this.$message.error(error?.response?.data?.message || '修改失败')
      }
    },

    refresh() {
      this.getNoticeUserList()
    }
  }
}
</script>
<style lang="scss" scoped>
.notice-user-setting {
  padding: 20px;
}

::v-deep(.el-card) {
  border: none;
}
</style>
